const getBlob = (url, cb) => {
  let xhr = new XMLHttpRequest()
  /* if(url.indexOf('fileserver/get?filename=')>-1){
    let splitName=url.split('?filename=')
    if(splitName&&splitName.length==2){
      url=`/down-api?filename=${splitName[1]}`;
    }
  } */
  xhr.open('GET', url, true)
  xhr.responseType = 'blob'
  xhr.onload = function () {
    if (xhr.status === 200) {
      cb(xhr.response)
    }
  }
  xhr.send()
}
const saveAs = (blob, filename) => {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename)
  } else {
    let link = document.createElement('a')
    let body = document.querySelector('body')
    link.href = window.URL.createObjectURL(blob)
    link.download = filename
    // fix Firefox
    link.style.display = 'none'
    body.appendChild(link)
    link.click()
    body.removeChild(link)
    window.URL.revokeObjectURL(link.href)
  }
}
export const download = (e) => {
  let index = e.url.lastIndexOf('.')
  let ext = e.url.substr(index + 1)

  //输出结果
  if (ext === 'png' || ext === 'jpg' || ext === 'jpeg') {
    let image = new Image()
    image.setAttribute('crossOrigin', 'anonymous')
    image.onload = function () {
    
      console.log(10090)
      let canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      let context = canvas.getContext('2d')
      context.drawImage(image, 0, 0, image.width, image.height)
      let url = canvas.toDataURL('image/png') //得到图片的base64编码数据
      let a = document.createElement('a') // 生成一个a元素
      let event = new MouseEvent('click') // 创建一个单击事件
      a.download = e.name // 设置图片名称
      a.href = url // 将生成的URL设置为a.href属性
      a.dispatchEvent(event) // 触发a的单击事件
    }
    
    /* if( e.url.indexOf('fileserver/get?filename=')>-1){
      let splitName= e.url.split('?filename=')
      if(splitName&&splitName.length==2){
        e.url=`/down-api?filename=${splitName[1]}`;
      }
    } */
    image.src = e.url
  } else if (ext == 'pdf') {
    getBlob(e.url, (blob) => {
      saveAs(blob, e.name)
    })
  } else {
    const blobUrl = e.url
    const a = document.createElement('a')
    a.style.display = 'none'
    a.target = '_blank'
    a.download = e.name
    a.href = blobUrl
    a.click()
    document.body.removeChild(a)
  }
}
